package com.fengxing.ams.web.action;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import com.fengxing.ams.pub.manager.intf.IConfigManager;
import com.fengxing.ams.pub.util.MD5Util;
import com.fengxing.ams.web.action.view.EnterpriseQueryVO;
import com.fengxing.ams.web.action.view.ResponseVO;
import com.fengxing.ams.web.action.view.StudentsQueryParamVO;
import com.fengxing.ams.web.action.view.StudentsViewVO;
import com.fengxing.ams.web.common.IContextManager;
import com.fengxing.ams.web.facade.intf.INotifyFacade;
import com.fengxing.ams.web.facade.intf.IOrderFacade;
import com.fengxing.ams.web.facade.intf.IStudentFacade;
import com.fengxing.ams.web.facade.intf.ISysManagerFacade;
import com.fengxing.ams.web.facade.intf.IUserFacade;
import com.fengxing.ams.web.facade.mouble.company.CompanyImportVO;
import com.fengxing.ams.web.facade.mouble.company.EnterpriseNotifyVO;
import com.fengxing.ams.web.facade.mouble.upload.UploadVO;
import com.fengxing.ams.web.facade.mouble.user.UserVO;

@Controller
@RequestMapping("enterprise")
@Transactional
public class EnrerprisetAction {
	
	private Log logger = LogFactory.getLog(EnrerprisetAction.class);
	
	@Autowired
	private IUserFacade userFacade;
	@Autowired
	private INotifyFacade notifyFacade;
	@Autowired
	private IContextManager contextManager;
	@Autowired
	private IConfigManager configManager;
	@Autowired
	private ISysManagerFacade sysManagerFacade;
	@Autowired
	private IOrderFacade orderFacade;
	@Autowired
	private IStudentFacade studentFacade;
	
	@RequestMapping(value = "/list.do", method = RequestMethod.POST)
	public @ResponseBody ResponseVO enterpriseQuery(@RequestBody EnterpriseQueryVO param) {
		ResponseVO vo = new ResponseVO();
		UserVO loginedUser = this.contextManager.getUserVO();
		//检查权限
		if (loginedUser == null) {
			vo.setSuccess(false);
			vo.setMessage("需要重新登录");
			return vo;
		}
		//检查角色是否为管理员角色
		if (!(loginedUser.getRoleIdList().contains(Long.valueOf(6L)) || loginedUser.getRoleIdList().contains(Long.valueOf(5L)))) {
			vo.setSuccess(false);
			vo.setMessage("没有权限进行该操作");
			return vo;
		}
		//调用facade进行动态查询
		Page<CompanyImportVO> page = this.studentFacade.queryEnterpriseList(param);
		StudentsViewVO view = new StudentsViewVO();
		List<CompanyImportVO> content = page.getContent();
		view.setData(content);
		view.setTotal(page.getTotalElements());
		vo.setData(view);
		vo.setMessage("请求成功！");
		return vo;
	}
	
	@RequestMapping(value = "/notify.do", method = RequestMethod.POST)
	public @ResponseBody ResponseVO enterpriseNotify(@RequestBody EnterpriseNotifyVO param) {
		ResponseVO vo = new ResponseVO();
		UserVO loginedUser = this.contextManager.getUserVO();
		//检查权限
		if (loginedUser == null) {
			vo.setSuccess(false);
			vo.setMessage("需要重新登录");
			return vo;
		}
		//检查角色是否为管理员角色
		if (!loginedUser.getRoleIdList().contains(Long.valueOf(6L))) {
			vo.setSuccess(false);
			vo.setMessage("没有权限进行该操作");
			return vo;
		}
		//调用facade进行动态查询
		this.studentFacade.saveNotify(param);
		vo.setMessage("请求成功！");
		return vo;
	}
	
	@RequestMapping(value = "/delete.do", method = RequestMethod.POST)
	public @ResponseBody ResponseVO enterpriseDelete(@RequestBody EnterpriseQueryVO param) {
		ResponseVO vo = new ResponseVO();
		UserVO loginedUser = this.contextManager.getUserVO();
		//检查权限
		if (loginedUser == null) {
			vo.setSuccess(false);
			vo.setMessage("需要重新登录");
			return vo;
		}
		//检查角色是否为管理员角色
		if (!(loginedUser.getRoleIdList().contains(Long.valueOf(6L)) || loginedUser.getRoleIdList().contains(Long.valueOf(5L)))) {
			vo.setSuccess(false);
			vo.setMessage("没有权限进行该操作");
			return vo;
		}
		//调用facade进行动态查询
		this.studentFacade.enterpriseDelete(param);
		vo.setMessage("请求成功！");
		return vo;
	}
	
	@RequestMapping(value = "/create.do", method = RequestMethod.POST)
	public @ResponseBody ResponseVO enterpriseDelete(@RequestBody CompanyImportVO param) {
		ResponseVO vo = new ResponseVO();
		UserVO loginedUser = this.contextManager.getUserVO();
		//检查权限
		if (loginedUser == null) {
			vo.setSuccess(false);
			vo.setMessage("需要重新登录");
			return vo;
		}
		//检查角色是否为管理员或学院角色
		if (!(loginedUser.getRoleIdList().contains(Long.valueOf(6L)) || loginedUser.getRoleIdList().contains(Long.valueOf(5L)))) {
			vo.setSuccess(false);
			vo.setMessage("没有权限进行该操作");
			return vo;
		}
		//调用facade进行动态查询
		this.studentFacade.enterpriseCreate(param);
		vo.setMessage("请求成功！");
		return vo;
	}
	
	@RequestMapping(value = "/upload.do" , method = RequestMethod.POST )  
    public @ResponseBody ResponseVO upload2(@RequestParam("type")String type, HttpServletRequest request,HttpServletResponse response) throws IllegalStateException, IOException {  
        //创建一个通用的多部分解析器  
        CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());  
        //判断 request 是否有文件上传,即多部分请求  
        if(multipartResolver.isMultipart(request)){  
            //转换成多部分request    
            MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest)request;  
            //取得request中的所有文件名  
            Iterator<String> iter = multiRequest.getFileNames();  
            while(iter.hasNext()){  
                //取得上传文件  
                MultipartFile file = multiRequest.getFile(iter.next());  
                if(file != null){  
                    //取得当前上传文件的文件名称  
                    String myFileName = file.getOriginalFilename();  
                    //如果名称不为“”,说明该文件存在，否则说明该文件不存在  
                    if(myFileName.trim() !=""){  
                        //重命名上传后的文件名  
                    	String temp = System.getProperty("java.io.tmpdir");
                    	String originalName = file.getOriginalFilename();
                    	String hash = MD5Util.md5(originalName+System.nanoTime());
                        String fileName = temp + hash + ".xls";   
                        //定义上传路径  
                        file.transferTo(new File(fileName));  
                        //保存记录到DB
                        UploadVO uploadVO = new UploadVO();
                        uploadVO.setFilePath(fileName);
                        uploadVO.setSize(file.getSize());
                        uploadVO.setStatus("未处理");
                        uploadVO.setUploadTime(new Date());
                        uploadVO.setOriginalName(originalName);
                        uploadVO.setType(type);
                        this.studentFacade.save(uploadVO);
                    }
                    
                }
                //记录上传该文件后的时间  
            }  
              
        }
        ResponseVO vo = new ResponseVO();
        vo.setSuccess(true);
        vo.setMessage("上传成功，请等待后台处理数据！");
        return vo;  
    }  
	
}
